package com.justreading.bio;


import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author LYJ
 * @Description 使用BIO 实现一个服务端
 * @date 2021 年 09 月 28 日 下午7:55
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("启动服务端....");
        while (true) {
            final Socket socket = serverSocket.accept();
            System.out.println(Thread.currentThread().getName() + "接受到一个链接的请求");
            executorService.execute(() -> {
                System.out.println("将链接交给" + Thread.currentThread().getName() + "去处理");
                handler(socket);
            });
        }
    }


    private static void handler(Socket socket) {
        InputStream inputStream = null;
        try {
            byte[] bytes = new byte[1024];
            inputStream = socket.getInputStream();
            System.out.println(Thread.currentThread().getName() + "开始读取客户端的数据：");
            while (true) {
                int read = inputStream.read(bytes);
                if(read != -1){
                    System.out.println(Thread.currentThread().getName() + "读取到客户端的数据：" + new String(bytes,0,read));
                }else{
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName() + "关闭socket链接");
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
